from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib import parse
import hashlib


class WXHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed_result = parse.urlparse(self.path)
        params = parsed_result.query
        url_path = parsed_result.path
        param_dict = {}
        if not params:
            self.response(404, "not found path: {}".format(url_path))
        for param_pair in params.split('&'):
            # print(param_pair)
            key, value = param_pair.split('=')
            param_dict[key] = value
        signature = param_dict.get('signature')
        timestamp = param_dict.get('timestamp')
        nonce = param_dict.get('nonce')
        echostr = param_dict.get('echostr')
        token = "xxxx"  # 请按照公众平台官网\基本配置中信息填写

        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        sha1.update(list[0].encode('utf-8'))
        sha1.update(list[1].encode('utf-8'))
        sha1.update(list[2].encode('utf-8'))
        # map(sha1.update, list)
        hashcode = sha1.hexdigest()
        print("handle/GET func: hashcode, signature: ", hashcode, signature)
        if hashcode == signature:
            return self.response(200, echostr)
        else:
            self.response(500, "not matched: {}".format(url_path))

    def response(self, status, msg):
        self.send_response(status)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(msg.encode('utf-8'))


def run(server_class=HTTPServer, handler_class=WXHandler):
    server_address = ('', 18100)
    httpd = server_class(server_address, handler_class)
    print("starting wx service...")
    httpd.serve_forever()


if __name__ == '__main__':
    run()